<?php

namespace App\Models;

use App\Http\Controllers\AxCallController;
use App\Http\Controllers\Easemob;
use App\Http\Controllers\WxPayController;
use App\Service\Push;
use App\User;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use App\Models\OrderGoods;
use Mrgoon\AliSms\AliSms;
use phpDocumentor\Reflection\Types\Self_;

class Order extends Model
{
    protected $table = 'c_orders';

    //关联多个订单商品
    public function ordergoods()
    {
        return $this->hasMany('App\Models\OrderGoods');
    }

    //关联一个订单商品
    public function order_goods()
    {
        return $this->hasOne('App\Models\OrderGoods');
    }

    public function aftersale()
    {
        return $this->hasOne('App\Models\AfterSales');
    }

    //所属工作室
    public function work()
    {
        return $this->hasOne('App\Models\DoctorWorks', "id", "work_id");
    }

    public function orderinvoices()
    {
        return $this->hasOne('App\Models\OrderInvoice', "order_id", "id");
    }

    //所属供应商
    public function distributor()
    {
        return $this->belongsTo('App\Models\AdminUser', "suppliers_id", 'id');
    }

    //获取患者用户
    public function sickPerson()
    {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     * 用户订单配送地址
     */
    public function orderaddress()
    {
        return $this->belongsTo('App\Models\OrderAddress','id',"order_id");
    }

    public static function getOrderStatus($data)
    {
        if ($data['pay_status'] == 0 && $data['order_status'] == 0) {
            return "待支付";
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 0 && $data['order_status'] == 0) {
            if($data['order_type'] ==3 || $data['order_type'] ==4){
                return "待接单";
            }else{
                return "待发货";
            }
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 1 && $data['receive_status'] == 0 && $data['order_status'] == 0) {
            if($data['order_type'] ==3 || $data['order_type'] ==4){
                return "问诊中";
            }else{
                return "待收货";
            }
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 1 && $data['receive_status'] == 1 && $data['evaluate_status'] == 0 && $data['order_status'] == 1) {
            return "待评价";
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 1 && $data['receive_status'] == 1  && $data['order_status'] == 1) {
            return "已完成";
        } elseif ($data['order_status'] == 2) {
            return "售后中";
        } elseif ($data['order_status'] == 3) {
            return "售后完成";
        } elseif ($data['order_status'] == 4) {
            return "已取消";
        }
    }

    //1待支付2待发货3待收货4待评论5售后
    public static function getOrderStatusNumber($data)
    {
        if ($data['pay_status'] == 0 && $data['order_status'] == 0) {
            return 1;
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 0 && $data['order_status'] == 0) {
            return 2;
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 1 && $data['receive_status'] == 0 && $data['order_status'] == 0) {
            return 3;
        } elseif ($data['pay_status'] == 1 && $data['delivery_status'] == 1 && $data['receive_status'] == 1 && $data['evaluate_status'] == 0 && $data['order_status'] == 1) {
            return 4;
        } elseif ($data['order_status'] == 2 || $data['order_status'] == 3) {
            return 5;
        }
    }




    /**
     * 获取排单时间表
     */
    public function getPlanTime($data)
    {
        if (!isset($data['rever_time']) && empty($data['rever_time'])) {
            return [];
        }
        if (!isset($data['rever_date']) && empty($data['rever_date'])) {
            return [];
        }
        $time = strtotime($data['rever_date'] . ' ' . $data['rever_time']);
        if ($time <= time()) {
            return [];
        }
        $where = [];
        $where[] = ['dates', '=', $data['rever_date']];
        $where[] = ['times', '=', $data['rever_time']];
        $where[] = ['work_id', '=', $data['work_id']];
        if ($data['order_type'] == 3) { //图文
            $type = 1;
        } elseif ($data['order_type'] == 4) { //电话
            $type = 2;
        }
        $where[] = ['type', '=', $type];
        return (new PlanTime())->where($where)->first();
    }


    /**
     * @param $data
     * @return array
     * 创建订单
     */
    public function createOrder($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
            if ($data['order_type'] == 1) {  //课程分账计算
                $go_num = (new Course())->where([['id', '=', $data['goods_id']]])->first();
                if ($go_num->work_id == $data['work_id']) {  //本工作室课程
                    $doc_price = self::setDocPrice($data['total_price'],$go_num->platform_rate);
                    $self_work_price = $doc_price['self_work_price'];
                    $platform_money = $doc_price['platform_money'];
                } else { //其他工作室
                    $share_work_price = sprintf("%.2f", $data['total_price'] * $go_num->commission_rate); //分享工作室得钱
                    $platform_money = sprintf("%.2f", $data['total_price'] * $go_num->platform_rate); //平台得钱
                    $s_money = $data['total_price'] - $share_work_price - $platform_money;  //本工作室得钱
                    $self_work_price = $s_money > 0 ? $s_money : 0;
                }
            }
            //判断收货地址是否存在
            if ($data['order_type'] == 2) {  //商品
                $address = (new Address())->getInfo($data['address_id']);
                if (empty($address)) {
                    return "请先填写收货地址!";
                }
                //查询库存
                $go_num = (new ProductGoods())->where([['id', '=', $data['goods_id']]])->first();
                if ($go_num->product_stock < $data['goods_num']) {
                    return "商品库存不足!";
                }
                //判断商品是否是自营  分账计算
                if ($go_num->product_source == 2) { //供应商
                    $supplier_price = $go_num->product_original_price * $data['goods_num'];
                    $platform_money =  sprintf("%.2f",($data['total_price'] - $supplier_price)  * $go_num->commission_rate); //平台得钱
                    $self_work_price = $data['total_price'] - $supplier_price - $platform_money;
                    $source = 2;
                }else{ //自营
                    if($go_num->supplier_work_id == $data['work_id']){  //本工作室商品
                        $doc_price = self::setDocPrice($data['total_price'],$go_num->commission_rate);
                        $self_work_price = $doc_price['self_work_price'];
                        $platform_money = $doc_price['platform_money'];
                    } else { //其他工作室   暂时没有其他工作室买自己工作室产品
                        $self_work_price = sprintf("%.2f", $data['total_price'] * $go_num->commission_rate);
                        $share_work_price =  sprintf("%.2f",$data['total_price'] - $self_work_price);
                    }
                    $source = 1;
                }
            }
            if ($data['order_type'] == 3) {  //图文
                $res = (new Doctor())->where([['id', '=', $data['goods_id']]])->first();
                if ($res->service_type == 0 || $res->service_type == 2) {
                    return "该医生未开通图文咨询功能,暂不能预约!";
                }
                if ($res->imagetext_price == 0 || $res->imagetext_time == 0) {
                    return "该医师未设置图文价格和咨询时间,暂不能预约!";
                }
                $this->consult_type = 2; //默认预约咨询  1待接诊2咨询预约
                //判断医师是否在线
                $ts['type'] = 2;
                $ts['user_id'] =$data['goods_id'];
                $tool_name = Tool::getUserNameForIm($ts);
                $logins_status = (new Easemob())->isOnline($tool_name['username']);
                if (isset($logins_status['data'][$tool_name['username']]) && $logins_status['data'][$tool_name['username']] == "online"){  //如果医生在线直接到待接诊
                    $this->consult_type = 1;
                } else {
                    //判断预约时间
                    $plan = $this->getPlanTime($data);
                    if (empty($plan)) {
                        return "时间已过,或该医生在该时间段没有排单计划!";
                    }
                }
                $doc_price = self::setDocPrice($data['total_price'],$res->platform_rate);
                $self_work_price = $doc_price['self_work_price'];
                $platform_money = $doc_price['platform_money'];
            }
            if ($data['order_type'] == 4) {  //电话
                $res = (new Doctor())->where([['id', '=', $data['goods_id']]])->first();
                if ($res->service_type == 0 || $res->service_type == 1) {
                    return "该医生未开通电话咨询功能,暂不能预约!";
                }
                if ($res->phone_price == 0 || $res->phone_time == 0) {
                    return "该医师未设置电话咨询价格和咨询时间,暂不能预约!";
                }
                $this->consult_type = 2; //默认预约咨询
                //判断预约时间
                $plan = $this->getPlanTime($data);
                if (empty($plan)) {
                    return "时间已过,或该医生在该时间段没有排单计划!";
                }
                $doc_price = self::setDocPrice($data['total_price'],$res->phone_rate);
                $self_work_price = $doc_price['self_work_price'];
                $platform_money = $doc_price['platform_money'];
            }
            $this->self_work_price = isset($self_work_price) ? $self_work_price : 0;
            $this->share_work_price = isset($share_work_price) ? $share_work_price : 0;
            $this->supplier_price = isset($supplier_price) ? $supplier_price : 0;
            $this->platform_money = isset($platform_money) ? $platform_money : 0;
            $this->sn = $this->orderNumber();
            $this->user_id = $data['user_id'];
            $this->work_id = $data['work_id'];
//            $this->address_id = isset($data['address_id']) ?: 0;
            $this->nums = isset($data['goods_num']) ? $data['goods_num'] : 1;
            $this->goods_num = isset($data['goods_num']) ? $data['goods_num'] : 1;
            $this->order_price = $data['order_price'];
            $this->pay_price = $data['pay_price'];
            $this->total_price = $data['total_price'];
            $this->logis_price = !empty($data['logis_price']) ? $data['logis_price'] : 0;
            $this->remarks = !empty($data['remarks']) ? $data['remarks'] : "";
            $this->order_type = $data['order_type'];
            $this->order_source = isset($source)?$source:1;
            $res = $this->save();
            if ($res) {
                $result = $this->setOrderGoods($data);
                if ($result === true) {
                    DB::commit(); // 提交事务
                    return ['order_id' => $this->id];
                } else {
                    DB::rollback(); // 回滚事务
                }
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }



    /**
     * 计算金额
     */
    public static function setDocPrice($price,$rate)
    {
        $platform_money = sprintf("%.2f", $price * $rate);
        $self_work_price = $price - $platform_money;
        $data['platform_money'] = $platform_money;
        $data['self_work_price'] = $self_work_price;
        return $data;
    }
    
    
    
    
    
    /***
     * @param $params
     * @return bool
     * 添加订单商品
     * 注释    商品类型(1:课程,2:商品3:打赏,4:图文质询,5:电话质询)
     */
    public function setOrderGoods($params)
    {
        $order_goods = new OrderGoods();
        if ($params['order_type'] == 1) { //课程
            $obj = new Course();
            $info = $obj->where([['id', '=', $params['goods_id']]])->first();
            $order_goods->goods_name = $info->course_title;
            $order_goods->goods_price = $info->course_price;
            $order_goods->goods_img = $info->course_img;
            $order_goods->specs_id = 0;
            $order_goods->goods_id = $params['goods_id'];
            $order_goods->user_id = $params['user_id'];
            $order_goods->work_id = $params['work_id'];
            $order_goods->order_id = $this->id;
            $order_goods->goods_type = 1;
            $order_goods->goods_num = isset($params['goods_num']) ? $params['goods_num'] : 1;;
            $order_goods->pay_price = $params['pay_price'];
            $order_goods->save();
        } elseif ($params['order_type'] == 2) { //商品
            $obj = new ProductGoods();
            $info = $obj->getInfo($params);
            //判断是否是供应商产品
            if ($info['product_source'] == 2) {
                $suppler['suppliers_id'] = $info['supplier_work_id'];
                $this->where([['id', '=', $this->id]])->update($suppler);
            }
            $order_goods->goods_name = $info['product_name'];
            $order_goods->goods_price = $info['product_retail_price'];
            $order_goods->goods_img = $info['product_image'];
            $order_goods->specs_id = 0;
            $order_goods->goods_id = $params['goods_id'];
            $order_goods->user_id = $params['user_id'];
            $order_goods->work_id = $params['work_id'];
            $order_goods->product_standard = isset($info['product_standard']) ? $info['product_standard'] : "";
            $order_goods->product_remark = isset($info['product_remark']) ? $info['product_remark'] : "";
            $order_goods->order_id = $this->id;
            $order_goods->goods_num = isset($params['goods_num']) ? $params['goods_num'] : 1;
            $order_goods->goods_type = 2;
            $order_goods->pay_price = $params['pay_price'];
            $res = $order_goods->save();
            if ($res) {
                $params['order_id'] = $this->id;
                $orderAddres = (new OrderAddress())->addOrderAddress($params);
                if ($orderAddres) {
                    return true;
                }
            }
            return false;
        } elseif ($params['order_type'] == 3 || $params['order_type'] == 4) {
            $obj = new Doctor();
            $info = $obj::getInfoById($params['goods_id']);
            $order_goods->goods_name = $info->real_name;
            $order_goods->goods_price = $params['pay_price'];
            $order_goods->goods_img = $info->profile;
            $order_goods->specs_id = $params['case_id'];
            $order_goods->goods_id = $params['goods_id']; //医生id
            $order_goods->user_id = $params['user_id'];
            $order_goods->work_id = $params['work_id'];
            $order_goods->order_id = $this->id;
            $order_goods->goods_type = $params['order_type'];
            $order_goods->goods_num = 1;
            $order_goods->pay_price = $params['pay_price'];
            $order_goods->rever_date = isset($params['rever_date']) ? $params['rever_date'] : "";
            $order_goods->rever_time = isset($params['rever_time']) ? $params['rever_time'] : "";
            if ($params['order_type'] == 3) {  //图文
                $order_goods->duration = $info->imagetext_time;
            } elseif ($params['order_type'] == 4) { //电话
                $order_goods->duration = $info->phone_time;
                $order_goods->phone = $params['phone'];
            }
            if (isset($params['describe']) && !empty($params['describe'])) {
                (new CaseDescribe())->where([['id', '=', $params['case_id']]])->update(['describe' => $params['describe']]);
            }
            $order_goods->save();
        }
        return true;
    }

    /***
     * @param $order_id
     * 确认收货/结束问诊
     */
    public static function confirmReceipt($order_id)
    {
        $orders = self::getOrderDetail($order_id);
        if ($orders->pay_status == 1 && $orders->delivery_status == 1 && $orders->receive_status == 0 && $orders->order_status == 0) {
            $orders->receive_status = 1;
            $orders->receive_time = date("Y-m-d H:i:s", time());
            $orders->order_status = 1;
            if ($orders->order_type == 3 || $orders->order_type == 4) {
                $orders->consult_status = 2;
                $orders->consult_end = 1; //主动结束
                $diff_time = time() - strtotime($orders->consult_time);
                $minute=floor($diff_time%86400/60);
                $second=floor($diff_time%86400%60);
                $orders->use_time =  $minute.":".$second;
                (new FinancialStatementsLog())::setCompleteConsultOrder($orders,$dl['use_time'] = $orders->use_time);
                (new Easemob())->sendGroupText("admin", $orders->chatgroup_id, "本次咨询已结束,祝您生活愉快!");
                //解散群组
                $filter['order_id'] = $order_id;
                (new Easemob())->dissolveChatRoom($filter);
            }elseif ($orders->order_type == 2){
                (new FinancialStatementsLog())->goodsOrderconfirmReceipt($order_id); //商品自动确认收货
                //发推送消息
                $push = new Push();
                $doc = (new Doctor())->where([['work_id', '=', $orders->work_id],['is_admin','=',1]])->first();
                $lt['type'] = 2;
                $lt['user_id'] = $doc->id;
                $lt['title'] = "收货消息提醒";
                $lt['content'] = "有用户在您工作室购买的商品，已确认收货，感谢您的服务。";
//                $push->pushToUser($lt);
            }
            return $orders->save();
        }
        return "该订单状态下不能确认收货!";
    }


    /***
     * @param $uid
     * 我的课程
     */
    public function getMyCourseList($uid)
    {
        $res = $this->where("user_id", "=", $uid)->where('order_type', '=', 1)->where([['pay_status','=',1],['order_status','<',2]])
            ->orderBy('id', 'desc')
            ->get();
        $orderGoods = new OrderGoods();
        $result = [];
        $host = new Url();
        foreach ($res as $k => $v) {
            $info = $orderGoods->with(['course', 'works'])->where("order_id", '=', $v->id)->first();
            if (!empty($info)) {
                $info_courses = $info->toArray();
                if ($info_courses['course']) {
                    $info_courses['course']['course_img'] = $host::getHttpHost() . 'upload/' . $info_courses['course']['course_img'];
                }
                $result[] = $info_courses;
            }
        }
        if (!empty($result)) {
            return $result;
        }
        return [];
    }

    /**
     * 客户端订单列表
     */
    public function getOrderList($param)
    {
        $field = "id";
        $asc = "desc";
        $where[] = ['user_id', '=', $param['user_id']];
        if (isset($param['types']) && !empty($param['types'])) {  //订单状态
            switch ($param['types']) {
                case 1: //待支付
                    $where[] = ['pay_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    break;
                case 2; //待发货
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    $where[] = ['order_type', '=', 2];
                    break;
                case 3; //待收货
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 1];
                    $where[] = ['receive_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    $where[] = ['order_type', '=', 2];
                    break;
                case 4; //待评价
                    $where[] = ['order_status', '=', 1];
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 1];
                    $where[] = ['receive_status', '=', 1];
                    $where[] = ['evaluate_status', '=', 0];
                    break;
                case 5; //售后
//                    $where[] = ['order_status', 'in', [2,3]];
                    $where[] = [function ($query) {
                        $query->whereIn('order_status', [2, 3]);
                    }];
                    $where[] = ['order_type', '=', 2];
                    break;
            }
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $ids = $this->getOrderByTitle($param['title']);
            $where[] = [function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            }];
        }
        $result = $this->with(['ordergoods', 'work', 'orderaddress','aftersale','orderinvoices'])->where($where)->orderBy($field, $asc)->paginate(15);
        if (!empty($result)) {
            $res = $result->toArray();
            $host = new Url();
            $area = new Area();
            foreach ($res['data'] as $k => &$v) {
                //设置订单状态
                $v["o_status"] = self::getOrderStatus($v);
                if ($v['ordergoods']) {
                    $v['ordergoods'][0]['goods_img'] = $host::getHttpHost() . 'upload/' . $v['ordergoods'][0]['goods_img'];
                }
                if ($v['work']) {
                    $v['work']['logo'] = $host::getHttpHost() . 'upload/' . $v['work']['logo'];
                }
                if ($v['orderaddress']) {
                    $v['orderaddress']['province'] = $area::getNameByCode($v['orderaddress']['province_id']);
                    $v['orderaddress']['city'] = $area::getNameByCode($v['orderaddress']['city_id']);
                    $v['orderaddress']['district'] = $area::getNameByCode($v['orderaddress']['district_id']);
                }
                if($v['orderinvoices']){
                    if($v['orderinvoices']['img']){
                        $v['orderinvoices']['img'] = $host::getHttpHost() . 'upload/' . $v['orderinvoices']['img'];
                    }
                }
            }
            return $res;
        }
        return [];
    }

    /**
     * @param $param
     * @return array
     * 接诊记录
     */
    public function getReceivePatientLog($param)
    {
        $field = "id";
        $asc = "desc";
        $where[] = ['user_id', '=', $param['user_id']];
        $where[] = ['work_id', '=', $param['work_id']];
        $where[] = ['receive_status', '=', 1];
        $where[] = [function ($query) {
            $query->whereIn('order_type', [3, 4]);
        }];
        $result = $this->with(['order_goods'])->where($where)->orderBy($field, $asc)->simplePaginate()->toArray();
        if (!empty($result)) {
            $host = new Url();
            $case = new CaseDescribe();
            foreach ($result['data'] as $k => &$v) {
                if ($v['order_goods']) {
                    $v['order_goods']['goods_img'] = $host::getHttpHost() . 'upload/' . $v['order_goods']['goods_img'];
                    $v['order_goods']['case_describe'] = $case::where([['id', '=', $v['order_goods']['specs_id']]])->first();
                }
            }
            return $result;
        }
        return [];
    }


    /**
     * 医护室订单列表
     */
    public function doctorOrderList($param)
    {
        $field = "id";
        $asc = "desc";
        $where[] = ['work_id', '=', $param['work_id']];
        if (isset($param['order_type'])) {  //订单类型
            switch ($param['order_type']) {
                case 1: //课程
                    $where[] = ['order_type', '=', 1];
                    break;
                case 2: //商品
                    $where[] = ['order_type', '=', 2];
                    break;
                case 3: //电话
                    $where[] = ['order_type', '=', 3];
                    break;
                case 4: //图文
                    $where[] = ['order_type', '=', 4];
                    break;
            }
        }
        if (isset($param['types']) && !empty($param['types'])) {  //订单状态
            switch ($param['types']) {
                case 1: //待支付
                    $where[] = ['pay_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    break;
                case 2: //待发货
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    break;
                case 3: //待收货
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 1];
                    $where[] = ['receive_status', '=', 0];
                    $where[] = ['order_status', '=', 0];
                    break;
                case 4: //待评价
                    $where[] = ['order_status', '=', 1];
                    $where[] = ['pay_status', '=', 1];
                    $where[] = ['delivery_status', '=', 1];
                    $where[] = ['receive_status', '=', 1];
                    $where[] = ['evaluate_status', '=', 0];
                    break;
                case 5: //售后
                    $where[] = ['order_status', '=', 2];
                    break;
            }
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $ids = $this->getOrderByTitle($param['title']);
            $where[] = [function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            }];
        }
        $result = $this->with(['ordergoods', 'work','aftersale', 'orderaddress'])->where($where)->orderBy($field, $asc)->paginate(15);
        if (!empty($result)) {
            $res = $result->toArray();
            $host = new Url();
            $area = new Area();
            foreach ($res['data'] as $k => &$v) {
                if ($v['order_status'] == 2 || $v['order_status'] == 3) {
                    $v["after_id"] = (new AfterSales())->where([["order_id", '=', $v['id']]])->value("id");
                }
                //设置订单状态
                $v["o_status"] = self::getOrderStatus($v);
                $v["o_status_num"] = self::getOrderStatusNumber($v);
                if ($v['ordergoods']) {
                    $v['ordergoods'][0]['goods_img'] = $host::getHttpHost() . 'upload/' . $v['ordergoods'][0]['goods_img'];
                }
                if ($v['work']) {
                    $v['work']['logo'] = $host::getHttpHost() . 'upload/' . $v['work']['logo'];
                }
                if ($v['orderaddress']) {
                    $v['orderaddress']['province'] = $area::getNameByCode($v['orderaddress']['province_id']);
                    $v['orderaddress']['city'] = $area::getNameByCode($v['orderaddress']['city_id']);
                    $v['orderaddress']['district'] = $area::getNameByCode($v['orderaddress']['district_id']);
                }
            }
            return $res;
        }
        return [];
    }


    //获取订单ID通过商品名称
    public function getOrderByTitle($title)
    {
        $where[] = ['c_order_goods.goods_name', 'like', "%$title%"];
        return $this->join('c_order_goods', 'c_orders.id', '=', 'c_order_goods.order_id')->where($where)->pluck('c_orders.id');
    }

    /****
     * @return string
     * 订单号生成
     */
    public function orderNumber()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /****
     * @param $order_id
     * @return mixed
     * 订单详情
     */
    public static function getOrderDetail($order_id)
    {
        $res = self::where([['id', '=', $order_id]])->with(['order_goods', "orderaddress"])->first();
        if ($res) {
            if ($res->ordergoods) {
                $host = new Url();
                $res->order_goods->goods_img = $host::getHttpHost() . 'upload/' . $res->order_goods->goods_img;
            }
            if ($res->orderaddress) {
                $add = new Area();
                $res->orderaddress->province = $add::getNameByCode($res->orderaddress->province_id);
                $res->orderaddress->city = $add::getNameByCode($res->orderaddress->city_id);
                $res->orderaddress->district = $add::getNameByCode($res->orderaddress->district_id);
            }
            return $res;
        }
        return false;
    }


    /**
     * 发货
     *
     */
    public function delivery($filter)
    {
        $res = $this->getOrderDetail($filter['order_id']);
        if ($res->order_source == 2) {
            return "该商品为供应商商品,您无权发货!";
        }
        if ($res->delivery_status == 1) {
            return "该订单已发货,不能重复发货!";
        }
        if ($res->order_type != 2) {
            return "该订单类型不能发货!";
        }
        $res->logis_company = $filter['logis_company'];
        $res->logis_num = $filter['logis_num'];
        $res->logis_code = isset($filter['logis_code']) ? $filter['logis_code'] : "";
        $res->delivery_status = 1;
        $res->delivery_time = date("Y-m-d H:i:s", time());
        //发推送消息
        $push = new Push();
        $works = (new DoctorWorks())->where([['id', '=', $res->work_id]])->first();
        $lt['type'] = 1;
        $lt['user_id'] = $res->user_id;
        $lt['title'] = "发货消息提醒";
        $lt['content'] = "您在" . $works->work_name . "购买的商品，已由医护人员安排发货，快递单号为" . $res->sn . "，请注意查看物流详情。";
        $push->pushToUser($lt);
        return $res->save();
    }

    /**
     * 取消原因(需要退款操作)
     *
     */
    public function cancel($filter)
    {
        $res = $this->getOrderDetail($filter['order_id']);
//        if ($res->order_source == 2) {
//            return "该商品为供应商商品,您无权取消!";
//        }
        if ($res->order_type == 3 || $res->order_type == 4) {  //咨询取消订单
            if ($res->delivery_status == 1 || $res->receive_status == 1 || $res->evaluate_status == 1 || $res->order_status != 0) {
                return "该订单已接单,不能取消该订单!";
            }
            if ($res->pay_status == 1) {
                if($res->pay_type ==1){
                    $data['sn'] = $res->sn;;
                    $data['return_sn'] = $this->orderNumber();;
                    $data['price'] = $res->order_price;;
                    (new WxPayController())->returnBack($data);
                }elseif ($res->pay_type ==2){
                    //退款操作
                    $lit['sn'] = $res->sn;
                    $lit['money'] = $res->order_price;
                    $lit['back_sn'] = $this->orderNumber();
                    $back = (new PaymentController())->doReturn($lit);
                    if ($back){
//                    退款成功,退还账单
                        $order_goods = $res->ordergoods[0];
                        (new FinancialStatementsLog())::setBackConsultOrder($res,$order_goods);
                    }
                }
                //给医生发短信
                if(!isset($filter['types']) && empty($filter['types'])){
                    //给用户发送短信医生已决绝
                    $ali_sms = new AliSms();
                    $phone = (new User())->where([['id','=',$res->user_id]])->value("phone");
                    $paras['name'] = $res->ordergoods[0]->goods_name;
                    //给用户发送短信
                    $ali_sms::sendMessage($phone,$paras,2);
                }
            }
        } else if($res->order_type ==2) {
            if ($res->order_type == 2) {  //商品
                if ($res->pay_status == 0) {
                    $res->cancel_type = isset($filter['cancel_type']) ? $filter['cancel_type'] : 0;
                    $res->cancel_reason = $filter['cancel_reason'];
                    $res->order_status = 4;
                    return $res->save();
                }
                if ($res->delivery_status == 1 || $res->receive_status == 1 || $res->evaluate_status == 1 || $res->order_status != 0) {
                    return "该订单已发货或者已取消,不能取消该订单!";
                }
                if ($res->pay_status == 1) {
                    //退款操作
                    if($res->pay_type ==1){
                        $data['sn'] = $res->sn;;
                        $data['return_sn'] = $this->orderNumber();;
                        $data['price'] = $res->order_price;;
                        (new WxPayController())->returnBack($data);
                    }elseif ($res->pay_type ==2){
                        $lit['sn'] = $res->sn;
                        $lit['money'] = $res->order_price;
                        $lit['back_sn'] = $this->orderNumber();
                        $back = (new PaymentController())->doReturn($lit);
                        if ($back) {
                            (new FinancialStatementsLog())->setGoodsOrderBack($filter['order_id']);
                            (new ProductGoods())->where([['id', '=', $res->ordergoods[0]->goods_id]])->decrement("product_sales", 1);
                            (new ProductGoods())->where([['id', '=', $res->ordergoods[0]->goods_id]])->increment("product_stock", 1);
                        }
                    }
                }
            } else { //课程订单
                return "该订单已发货或者已取消,不能取消该订单!";
            }
        }else if ($res->order_type ==1){ //课程
            if ($res->pay_status == 0) {
                $res->cancel_type = isset($filter['cancel_type']) ? $filter['cancel_type'] : 0;
                $res->cancel_reason = $filter['cancel_reason'];
                $res->order_status = 4;
                return $res->save();
            }
        }
        $res->cancel_type = isset($filter['cancel_type']) ? $filter['cancel_type'] : 0;
        $res->cancel_reason = $filter['cancel_reason'];
        $res->order_status = 4;
        return $res->save();
    }

    /**
     * @param $doctor_id
     * @param $user_name
     * @return mixed
     * 名称搜索,获取病例id
     */
    public function getCaseIds($doctor_id, $user_name)
    {
        $order_goods = new OrderGoods();
        $w[] = ['c_order_goods.goods_id', '=', $doctor_id];
        $w[] = ['c_case_describes.name', 'like', '%' . $user_name . '%'];
        $res = $order_goods->join('c_case_describes', 'c_order_goods.specs_id', '=', 'c_case_describes.id')
            ->where($w)->distinct()->pluck("c_case_describes.id");
        return $res;
    }


    /**
     * 医护端获取咨询列表
     *
     */
    public function getDoctorConsultList($filter)
    {
        $where[] = ['c_orders.work_id', '=', $filter['work_id']];
        $where[] = ['c_order_goods.goods_id', '=', $filter['doctor_id']];
        $where[] = ['c_orders.pay_status', '=', 1];
        if (isset($filter['consult_type'])) { //1待接诊2咨询预约
            $where[] = ['c_orders.consult_type', '=', $filter['consult_type']];
            $where[] = ['c_orders.consult_status', '=', 0];
            $where[] = ['c_orders.order_status', '=', 0];

        }
        if (isset($filter['consult_status'])) { //已接单(咨询中)
            $where[] = ['c_orders.consult_status', '=', $filter['consult_status']];
            $where[] = ['c_orders.receive_status', '=', 0];
            $where[] = ['c_orders.order_status', '=', 0];

        }
        if (isset($filter['receive_status'])) { //咨询结束
            $where[] = ['c_orders.receive_status', '=', $filter['receive_status']];
            $where[] = ['c_orders.order_status', '>=', 1];
        }
        if (isset($filter['user_name'])) { //名称搜索
            $case_id = $this->getCaseIds($filter['doctor_id'], $filter['user_name']);
            $where[] = [function ($query) use ($case_id) {
                $query->whereIn('specs_id', $case_id);
            }];
        }
        $res = $this->join('c_order_goods', 'c_orders.id', '=', 'c_order_goods.order_id')
            ->select("c_order_goods.*", "c_orders.*")
            ->whereIn("order_type", [3, 4])
            ->orderBy("c_orders.id", "desc")
            ->where($where)
            ->simplePaginate()->toArray();
        $case = new CaseDescribe();
        $host = new Url();
        if (!empty($res['data'])) {
            $now = time();
            foreach ($res['data'] as $k => &$v) {
                $v['case_info'] = $case->where([['id', '=', $v['specs_id']]])->first();
//                $files = $report->where([['case_id', '=', $v['specs_id']]])->get();
                $time_str = strtotime($v['consult_time']);
                $end_second = $time_str + $v['duration'] * 60;
                $v['end_second'] = 0;
                if($time_str < $now && $now < $end_second){
                    $v['end_second'] = $end_second - $now;
                }
                $end_time = date("Y-m-d H:i:s", $end_second);
                $v['end_time'] = $end_time;
                if ($v['receive_status'] == 0) {
                    $v['remain_time'] = $this->changeTimeType($end_second - $now);//date("H:i:s", ($end_second - $now));//剩余时间
                } else {
                    $v['remain_time'] = 0;
                }
                //咨询人头像
                $image = (new User())->where([['id', '=', $v['user_id']]])->value("image");
                if ($image) {
                    $v['image'] = $host::getHttpHost() . 'upload/' . $image;
                } else {
                    $v['image'] = $image;
                }
                if (!empty($v['case_info']->picture)) {
                    $files = $v['case_info']->picture;
                    foreach ($files as $kk => &$vv) {
                        $vv = $host::getHttpHost() . 'upload/' . $vv;
                    }
                    $v['case_info']->picture = $files;
                }
            }
        }
        return $res;
    }

    /**
     * @param $time
     * @return string
     * 获取分钟
     */
    public function changeTimeType($time){
        if ($time >3600){
            $hours =intval($time/3600);
            $minutes = $time % 3600;
            $times = $hours.":".gmstrftime('%M:%S',$minutes);
        }else{
            $times = gmstrftime('%H:%M:%S',$time);
        }
        return $times;
    }


    /***
     * @param $filter
     * 获取患者详情
     */
    public function patientDetail($filter)
    {
        $res = $this->getOrderDetail($filter['order_id']);
        if ($res->ordergoods[0]->goods_id != $filter['doctor_id']) {
            return "该订单不属于您的订单,您无权查看!";
        }
        $case = new CaseDescribe();
//        $report = new CaseReport();
        $host = new Url();
        $case_info = $case->where([['id', '=', $res->ordergoods[0]->specs_id]])->first();
//        $files = $report->where([['case_id', '=', $case_info->id]])->get();
        $time_str = strtotime($res->consult_time);
        $end_time = date("Y-m-d H:i:s", $time_str + $res->duration * 60);
        $res->end_time = $end_time;
        $res->remain_time = date("H:i:s", $time_str + $res->duration * 60 - time());
        if (!empty($case_info->picture)) {
            $files = $case_info->picture;
            foreach ($files as $kk => &$vv) {
                $vv = $host::getHttpHost() . 'upload/' . $vv;
            }
            $case_info->picture = $files;
        }
        $res->case_info = $case_info;
        return $res->toArray();
    }


    /**
     * 医师加时
     */
    public function addTime($filter)
    {
        $res = $this->where([['chatgroup_id', '=', $filter['group_id']]])->with(['ordergoods'])->first();
        if (empty($res)) {
            return "该订单不存在,你不能加时!";
        }
        if ($res->ordergoods[0]->goods_id != $filter['doctor_id']) {
            return "该订单不属于您的订单,您无权加时!";
        }
        $data = (new OrderGoods())->where([['order_id', '=', $res->id]])
            ->increment("duration", $filter['minute']);
        if ($data) {
            return true;
        }
        return "加时失败";
    }

    /**
     * 确认接单
     */
    public function confirm($filter)
    {
        $res = $this->getOrderDetail($filter['order_id']);
        if ($res->pay_status != 1) {
            return "该订单没有支付,不能接单!";
        }
        if ($res->delivery_status != 0) {
            return "该订单已被接单,不能重复接单!";
        }
        if ($res->order_type != 3 && $res->order_type != 4) {
            return "订单类型不正确,不能接单!";
        }
        if ($res->ordergoods[0]->goods_id != $filter['doctor_id']) {
            return "该订单不属于您的订单,您无权接单!";
        }
        $array = ['delivery_status' => 1, 'delivery_time' => date("Y-m-d H:i:s", time())];
        if ($res->consult_type == 1) { //如果是待接诊,接单后直接开始咨询
            $array = ['delivery_status' => 1, 'delivery_time' => date("Y-m-d H:i:s", time()),
                'consult_status' => 1, 'consult_time' => date("Y-m-d H:i:s", time())];
            //创建群
            $case_user = (new CaseDescribe())->where([['id','=',$res->ordergoods[0]->specs_id]])->first();
            //创建咨询群
            $doc['type']  = 2;
            $doc['user_id']  = $res->ordergoods[0]->goods_id;
            $doc_user =  Tool::getUserNameForIm($doc);
            $us['type']  = 1;
            $us['user_id']  = $res->user_id;
            $us_user =  Tool::getUserNameForIm($us);
            $dd['admin'] = $doc_user['username'] ;
            $dd['group_name'] = $case_user->name."咨询".$res->ordergoods[0]->goods_name.'工作室';
            $dd['private_group_desc'] = "订单号".$res->sn."_".$res->ordergoods[0]->rever_date." ".$res->ordergoods[0]->rever_date."开始咨询" ;
            $dd['user'] = $us_user['username'];
            $dd['order_id'] = $res->id;
            $ff = (new Easemob())->makeChatRoom($dd);
            $up_notice['order_id'] = $res->id;
            $up_notice['mes'] = "咨询结束后,该聊天室会自动解散!";
            (new Easemob())->updateGroupAnnouncement($up_notice);
            //发送群消息
            $group_id = $this->where([['id','=',$filter['order_id']]])->value("chatgroup_id");
            (new Easemob())->sendGroupText("admin",$group_id,"本次咨询即将开始,咨询时间有限,请注意观察时间,时间到达后,本聊天室将自动解散!");
        }
        $data = $this->where([['id', '=', $filter['order_id']]])
            ->update($array);
        if ($data) {
            $ali_sms = new AliSms();
            if(!empty($res->ordergoods[0]->phone)){
                $phone = $res->ordergoods[0]->phone;
            }else{
                $phone = (new User())->where([['id','=',$res->user_id]])->value("phone");
            }
            $paras['name'] = $res->ordergoods[0]->goods_name;
            if(!empty($res->consult_type) && $res->consult_type ==1){
                $paras['time'] = date("Y-m-d H:i:s",time());
            }else{
                $paras['time'] = $res->ordergoods[0]->rever_date ." ".$res->ordergoods[0]->rever_time;
            }
            //给用户发送短信
            $ali_sms::sendMessage($phone,$paras,1);
            if(isset($group_id)){
                return $group_id;
            }
            return true;
        }
        return "加时失败";
    }

    /**
     * 开始咨询
     */
    public function startConsult($filter)
    {
        $res = $this->getOrderDetail($filter['order_id']);
        if ($res->pay_status != 1) {
            return "该订单没有支付,不能咨询!";
        }
        if ($res->delivery_status == 0) {
            return "请先确认订单后再进行咨询!";
        }
        if ($res->consult_status != 0) {
            return "该订单已被咨询过,不能重复咨询!";
        }
        if ($res->ordergoods[0]->goods_id != $filter['doctor_id']) {
            return "该订单不属于您的订单,您无权咨询!";
        }

        if ($res->order_type == 3) { //图文
            $case_user = (new CaseDescribe())->where([['id', '=', $res->ordergoods[0]->specs_id]])->first();
            //创建咨询群
            $doc['type'] = 2;
            $doc['user_id'] = $filter['doctor_id'];
            $doc_user = Tool::getUserNameForIm($doc);
            $us['type'] = 1;
            $us['user_id'] = $res->user_id;
            $us_user = Tool::getUserNameForIm($us);
            $dd['admin'] = $doc_user['username'];
            $dd['order_id'] = $res->id;
            $dd['group_name'] = $case_user->name . "咨询" . $res->ordergoods[0]->goods_name . '工作室';
            $dd['private_group_desc'] = "订单号" . $res->sn . "_" . $res->ordergoods[0]->rever_date . " " . $res->ordergoods[0]->rever_date . "开始咨询";
            $dd['user'] = $us_user['username'];
            $group_make = (new Easemob())->makeChatRoom($dd);  //创建群
            if($group_make ==false){
                return "创工作室失败,请重新再试!";
            }
            $up_notice['order_id'] = $res->id;
            $up_notice['mes'] = "咨询结束后,该聊天室会自动解散!";
            (new Easemob())->updateGroupAnnouncement($up_notice); //修改群公告
            //发送群消息
            $group_id = $this->where([['id', '=', $filter['order_id']]])->value("chatgroup_id");
            (new Easemob())->sendGroupText("admin", $group_id, "本次咨询即将开始,咨询时间有限,请注意观察时间,时间到达后,本聊天室将自动解散!");
        } elseif ($res->order_type == 4) {
            //绑定小号
            $user = (new User())->where([['id', '=', $res->user_id]])->first();
            if(!empty($res->ordergoods[0]->phone)){
                $u_phone = $res->ordergoods[0]->phone;
            }else{
                $u_phone = $user->phone;
            }
            $data_bind['mid_phone'] = config("omnipay.Numbers");// $mid_phone[0];//"02160556770";
            $data_bind['a_phone'] = (new Doctor())->where([['id','=',$res->ordergoods[0]->goods_id]])->value("account"); //$res->ordergoods[0]->phone;
            $data_bind['b_phone'] =$u_phone;
            $data_bind['time'] =$res->ordergoods[0]->duration * 60;
            $group_make = (new AxCallController())->doBindAxbPhone($data_bind); //绑定axb
            if($group_make ==false){
                return "小号绑定失败,请联系平台客服处理!";
            }
            $group_id =  config("omnipay.Numbers");
//            $array['chatgroup_id'] = $group_id;
            $this->setMidPhoneLog($group_id,$res->ordergoods[0]->duration,$res->id,$data_bind['a_phone'],$data_bind['b_phone']);
        }
        if($group_make=="success"){
            $array = ['consult_status' => 1, 'consult_time' => date("Y-m-d H:i:s", time()),'chatgroup_id'=>$group_id];
            $this->where([['id', '=', $filter['order_id']]])->update($array);
//            (new Doctor())->where([['id', '=', $filter['doctor_id']]])->increment('consult_num');
            $td['type'] = $res->order_type;
            $td['nums'] = $group_id;
            return $td;
        }
        return "开始咨询失败";
    }

    /**
     * @param $result
     * 获取小号
     */
    public function getMidPhone()
    {
        $numbers = config("omnipay.Numbers");
        $mid_phone = new MidPhoneLog();
        $log = [];
        foreach ($numbers as $k => $v) {
            $find = $mid_phone->where([['midphone', '=', $v], ['state', '=', 1]])->first();
            if ($find) {
                continue;
            }
            $log[] = $v;
            break;
        }
        if (empty($log)) {
            return false;
        }
        return $log;
    }

    /**
     *
     */
    public function setMidPhoneLog($phone, $duration,$order_id,$a,$b)
    {
        $data['midphone'] = $phone;
        $data['a_phone'] = $a;
        $data['b_phone'] = $b;
        $data['duration'] = $duration;
        $data['order_id'] = $order_id;
        $data['state'] = 1;
        $data['start_time'] = date("Y-m-d H:i:s", time());
        $data['end_time'] = date("Y-m-d H:i:s", time() + 60 * $duration);
        return (new MidPhoneLog())->add($data);
    }

    /**
     * @param $order_id
     * 催发货
     */
    public static function urgeDelivery($order_id)
    {
        $res = self::getOrderDetail($order_id);
        if($res->order_source == 1){ //1工作室商品2供应商商品
            $doctor = (new Doctor())->where([['work_id','=',$res->work_id],['is_admin','=',1]])->first();
            $username = 'doctor_' . config("omnipay.Im.salt") . $doctor->id;
            $param['user'] = $username;
            $param['title'] = "催发货提醒";
            $param['content'] = "订单号".$res->sn."用户已催发货,请及时发货";
            $param['sub_title'] = "催发货提醒";
            (new Easemob())->sendSinglePush($param); //推送
            $pa['username'] = $username;
            $pa['text'] = "订单号".$res->sn."用户已催发货,请及时发货";;
            $res = (new Easemob())->sendTextBySdk($pa); //发消息
            if($res){
                return true;
            }
        }elseif ($res->order_source == 2){


        }
        return false;
    }
    
    
    /***
     * 通过群id获取剩余时间
     */
    public static function getTimeBYGroupid($data)
    {
       $info =  self::where([['chatgroup_id','=',$data['group_id']]])->with(['order_goods'])->first();
       if(empty($info)){
           return "该咨询订单还没有开始!";
       }
       if($info->receive_status == 1 && $info->order_status == 1){
           return "该咨询订单已完成!";
       }
       $con_time = strtotime($info->consult_time);
       $now = time();
       if($con_time > $now){
           return "该咨询订单还没有开始!";
       }
       $end = $con_time + $info->order_goods->duration* 60;
       if($end < $now){
           return "该咨询订单已结束!";
       }
       $order_goods =(new OrderGoods())->where([['order_id','=',$info->id]])->first();
       $dd['time'] = ceil($end-$now);
       $dd['doc_name'] =$order_goods->goods_name;
       return $dd;
    }

    /**
     * @param $param
     * 获取退货地址
     */
    public function getReturnAddress($param)
    {
        $res = self::getOrderDetail($param['order_id']);
        if ($res->order_type != 2) {
            return "该订单类型不符!";
        }
        $goods = (new ProductGoods())->where([['id', '=', $res->order_goods->goods_id]])->first();
        if (empty($goods)) {
            return "该订单商品已不存在,无法获取退货地址!";
        }
        if ($goods->product_source == 1) { //工作室
            $work = (new DoctorWorks())->where([['id', '=', $goods->supplier_work_id]])->first();
            $province = (new Area())::getNameByCode($work->province_id);
            $city = (new Area())::getNameByCode($work->city_id);
            $district_id = (new Area())::getNameByCode($work->district_id);
            $detail = $work->address;
        } elseif ($goods->product_source == 2) { //供应商
            $supplier = (new Address())->where([['type', '=', 1], ['user_id', '=', $goods->supplier_work_id]])->first();
            if(empty($supplier)){
                return "该供应商还没有设置退货地址!";
            }
            $province = (new Area())::getNameByCode($supplier->province_id);
            $city = (new Area())::getNameByCode($supplier->city_id);
            $district_id = (new Area())::getNameByCode($supplier->district_id);
            $detail = $supplier->detail;
        }
        $lit['province'] = $province;
        $lit['city'] = $city;
        $lit['district_id'] = $district_id;
        $lit['detail'] = $detail;
        return $lit;
    }


}
